<?php

namespace App\Console\Commands;

use App\Http\Common\Constant;
use App\Models\BonusPool;
use App\Models\Member;
use App\Models\MemberIncomeLog;
use Illuminate\Console\Command;
use App\Models\MemberBonusQueue as mbq;

class MemberBonusQueue extends Command
{
    /**
     * 会员中奖
     *
     * @var string
     */
    protected $signature = 'member_bonus_queue';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description member_bonus_queue';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        while (1) {
            // 资金池
            $bonus_pool = BonusPool::where('id', 1)->first();
            // 如果资金池大于设置金额就反钱给用户
            if ($bonus_pool->usable_money > Constant::MEMBER_BONUS_MONEY) {

                $member_bonus_queue = mbq::where('status', '0')->first();

                try {
                    \DB::beginTransaction();

                    if ($member_bonus_queue) {
                        $bonus_pool->usable_money -= Constant::MEMBER_BONUS_MONEY;
                        $bonus_pool->save();
                        // 修改队列奖励
                        $member_bonus_queue->status = 1;
                        $member_bonus_queue->bonus_time = date("Y-m-d H:i:s");
                        $save = $member_bonus_queue->save();
                        if (!$save) {
                            throw new \Exception("修改队列奖励写入失败");
                        }

                        // 写入会员奖金
                        $member = Member::where('id', $member_bonus_queue->member_id)->first();
                        $member->useable_bonus_money += Constant::MEMBER_BONUS_MONEY;
                        $member->total_bonus_money += Constant::MEMBER_BONUS_MONEY;
                        $save = $member->save();
                        if (!$save) {
                            throw new \Exception("会员奖金写入失败");
                        }

                        // 写入会员奖金日志
                        $member_income_log = new MemberIncomeLog();
                        $member_income_log->member_id = $member_bonus_queue->member_id;
                        $member_income_log->money = Constant::MEMBER_BONUS_MONEY;
                        $save = $member_income_log->save();
                        if (!$save) {
                            throw new \Exception("会员奖金日写入失败");
                        }
                    }


                    \DB::commit();
                } catch (\Exception $e) {
                    \DB::rollBack();
                    var_dump($e->getMessage());
                }
            } else {
                echo 'game over';
                sleep(10);
            }
        }
    }
}
